import Vue from "vue";

Vue.directive("debounce", {
    bind: (el, binding) => {
        let [fn, type = "input", time = 800] = binding.value;
        let cbFun;
        el.addEventListener(
            type,
            () => {
                if (cbFun) clearTimeout(cbFun);
                cbFun = setTimeout(() => {
                    fn();
                }, time);
            },
            true
        );
    },
});

Vue.directive("num", {
    bind(el, binding) {
        let { decimals = 2 } = binding.value;
        el.addEventListener(
            "input",
            () => {
                if (el.children[0].value === "") {
                    return;
                }
                let valueArr = el.children[0].value.split(".");
                if (valueArr.length === 1 || decimals === 0) {
                    el.children[0].value = valueArr[0].replace(/[^0-9]/g, "");
                } else if (valueArr.length >= 2) {
                    if (valueArr[0] === "") {
                        el.children[0].value = "";
                        return;
                    }
                    let part1 = valueArr[0].replace(/[^0-9]/g, "");
                    let part2 = valueArr[1].replace(/[^0-9]/g, "");
                    if (part2.length > decimals) {
                        part2 = part2.substring(0, decimals);
                    }
                    el.children[0].value = part1 + "." + part2;
                }
            },
            true
        );
    },
});
